﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace regex
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            UpdateMatches();
        }

        private void TxtText_TextChanged(object sender, EventArgs e)
        {
            UpdateMatches();
        }

        private void UpdateMatches()
        {
            try
            {
                var pattern = TxtPattern.Text;
                var search = TxtText.Text;
                var regex = new Regex(pattern);
                var matches = regex.Matches(search);
                
                // Clear any Formatting Previously Applied.
                TxtMatches.SelectAll();
                TxtMatches.SelectionColor = Color.Black;
                TxtMatches.SelectionFont = new Font(TxtMatches.Font, FontStyle.Regular);

                TxtMatches.Text = search;
                foreach (Match match in matches)
                {
                    TxtMatches.SelectionStart = match.Index;
                    TxtMatches.SelectionLength = match.Length;
                    TxtMatches.SelectionColor = Color.Red;
                    TxtMatches.SelectionFont = new Font(TxtMatches.SelectionFont, FontStyle.Bold);
                }
            }
            catch (Exception)
            {
                TxtMatches.ForeColor = Color.Red;
                TxtMatches.Text = "An error ocurred parsing the RegEx, is the pattern valid?";
            }
        }

        private void TxtPattern_TextChanged(object sender, EventArgs e)
        {
            UpdateMatches();
        }

        bool RequiredTextBoxValid(TextBox control, Control controlToAddToErrorProvider, string message)
        {
            bool invalid = string.IsNullOrEmpty(control.Text);
            errProv.SetError(controlToAddToErrorProvider,
                             invalid ? message : string.Empty);
            return !invalid;
        }

        private void TxtText_Validating(object sender, CancelEventArgs e)
        {
            e.Cancel = !RequiredTextBoxValid(TxtText, LblEnterText,
                "Please enter text to find RegEx matches in.");
        }

        private void TxtPattern_Validating(object sender, CancelEventArgs e)
        {
            e.Cancel = !RequiredTextBoxValid(TxtPattern, LblEnterRegEx,
                "Please enter a RegEx Pattern.");
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            errProv.Clear();
        }

        private void TxtPattern_Validated(object sender, EventArgs e)
        {
            errProv.SetError(LblEnterRegEx, string.Empty);
        }
    }
}